package cn.itcast.order.service;

import cn.itcast.order.client.UserClient;
import cn.itcast.order.mapper.OrderMapper;
import cn.itcast.order.pojo.Order;
import cn.itcast.order.pojo.User;
import com.alibaba.fastjson.JSON;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

//@DefaultProperties(defaultFallback = "allMethodFallBack")  //指向全局降级处理
@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

//    @Autowired
//    private RestTemplate restTemplate;

    @Autowired
    private UserClient userClient;

//    @HystrixCommand(fallbackMethod = "queryOrderByIdFallback")  // 指向降级方法
//    @HystrixCommand
    public String queryOrderById(Long orderId) {
        // 1.查询订单
        Order order = orderMapper.findById(orderId);
        // 2.调用RestTemplate
        // User user = restTemplate.getForObject("http://localhost:8081/user/" + order.getUserId(), User.class);
//        User user = restTemplate.getForObject("http://userservice/user/" + order.getUserId(), User.class);

        User user = userClient.findById(order.getUserId());

        // 3.存放user对象到order
        order.setUser(user);
        // 4.返回
        return JSON.toJSONString(order);
    }

    // 降级
    public String queryOrderByIdFallback(Long orderId){
        return "服务器在忙，稍后再试";
    }

    // 全局降级
    public String allMethodFallBack(){
        return "服务器真的在忙，别再试了";
    }
}
